﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using FileManager_Client.BusinessLogic;
using FileManager_Client.BusinessLogic.FileManagerUserService;
using FileManager_Client.PresentationLayer.NewUi;
using FileManager_Client.Utility;

namespace FileManager_Client.PresentationLayer
{
    public partial class FileSerch : Form
    {
        private UserLoginResult userSession;
        private WaitDialogForm _waitBeforeLogin;
        private static  object lockWait = new object();
        private FileService fileService;
        private ServerFiles _serverFiles;
        public FileSerch(ServerFiles serverFiles)
        {
            InitializeComponent();
            this.skinEngine1.SkinFile = "office2007.ssk";
            dtpBeginTime.Text = "";
            dtpEndtiome.Text = "";
            userSession = CacheGlobal.GetCache(GlobalString.System_Config_String.UserSession) as UserLoginResult;
            _serverFiles = serverFiles;
            fileService = new FileService();
        }

        private void SearchFileMethod()
        {
            if (string.IsNullOrEmpty(txtFileName.Text.Trim()) &&
               string.IsNullOrEmpty(txtAuthor.Text.Trim()) &&
               string.IsNullOrEmpty(dtpBeginTime.Text) &&
               string.IsNullOrEmpty(dtpEndtiome.Text))
            {
                XtraMessageBox.AllowCustomLookAndFeel = false;
                XtraMessageBox.Show("没有包含任何搜索条件!", GlobalString.System_Config_String.MbxInfoStr,
                                          MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                backgroundWorkerSearchFile = new BackgroundWorker();
                backgroundWorkerSearchFile.DoWork += backgroundWorkerSearchFile_DoWork;
                var fileSearchArgs = new FileSearchArgs
                {
                    CompanyIdk__BackingField = userSession.CompanyIdk__BackingField,
                    FileAuthk__BackingField = txtAuthor.Text.Trim(),
                    FileNamek__BackingField = txtFileName.Text.Trim()
                };
                DateTime beginTime;
                var isTime = DateTime.TryParse(dtpBeginTime.Text, out beginTime);
                fileSearchArgs.BeginTimek__BackingField = !isTime ? DateTime.Now : beginTime;
                DateTime endTime;
                isTime = DateTime.TryParse(dtpEndtiome.Text, out endTime);
                fileSearchArgs.EndTimek__BackingField = !isTime ? fileSearchArgs.BeginTimek__BackingField : endTime;
                backgroundWorkerSearchFile.RunWorkerAsync(fileSearchArgs);
                lock (lockWait)
                {
                    _waitBeforeLogin = new WaitDialogForm(GlobalString.System_Config_String.FileSearchStr,
                                                          GlobalString.System_Config_String.MbxInfoStr)
                    {
                        BackColor = BackColor
                    };
                    _waitBeforeLogin.Hide();
                }
                _waitBeforeLogin.Show();
            }
        }

        private BackgroundWorker backgroundWorkerSearchFile;
        private void BtnBeginSearch_Click(object sender, EventArgs e)
        {
            SearchFileMethod();
        }

        void backgroundWorkerSearchFile_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var fileSearchArgs = e.Argument as FileSearchArgs;
                var result = fileService.SearchFile(fileSearchArgs);
                Invoke((EventHandler)delegate
                {
                    _waitBeforeLogin.Close();
                });
                if(result.ResultExceptionk__BackingField == BaseExceptionEnum.SearchFileException)
                {
                    XtraMessageBox.Show("远程服务器异常，请联系管理员!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                      MessageBoxIcon.Error);
                    Invoke((EventHandler)delegate
                    {
                        Close();
                    });
                }
                else
                {
                    var tempObjCollection = result.FileCollectionk__BackingField.Select(fileResult => new SearchFileClass
                                                                                                          {
                                                                                                              CreateName = fileResult.CreateNamek__BackingField, FileName = fileResult.FileNamek__BackingField, FilePath = fileResult.FilePathk__BackingField, FolderSid = fileResult.IsFilek__BackingField ? fileResult.ParentIdk__BackingField : fileResult.FileSidk__BackingField, IsJustMe = false, IsCreate = true, IsRead = true, IsUpdate = true, IsDelete = true, LastUpdate = fileResult.UpdateNamek__BackingField, UpdateTime = fileResult.UpdateTimek__BackingField.ToString(),
                                                                                                          }).ToList();
                    olv_SearchFile.SetObjects(tempObjCollection);
                }
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("backgroundWorkerSearchFile_DoWork has problem", ex);
                XtraMessageBox.Show("搜索文件失败!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                Invoke((EventHandler)delegate
                {
                    Close();
                });
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            olv_SearchFile.ClearObjects();
            olv_SearchFile.Items.Clear();
        }

        private void tsmi_MoveToFileFolder_Click(object sender, EventArgs e)
        {
            if (olv_SearchFile.SelectedObject == null) return;
            var obj = olv_SearchFile.SelectedObject as SearchFileClass;
            _serverFiles.Invoke((EventHandler)delegate
            {
                _serverFiles.UpdateListView(obj.FolderSid);
            });
            Invoke((EventHandler)delegate
            {
                Close();
            });
        }

        private void cms_SearchFile_Opening(object sender, CancelEventArgs e)
        {
            if (null == olv_SearchFile.SelectedObject)
                e.Cancel = true;
        }

        private void btnEndSearch_Click(object sender, EventArgs e)
        {
            if(null != backgroundWorkerSearchFile && backgroundWorkerSearchFile.IsBusy)
                backgroundWorkerSearchFile.CancelAsync();
            if(null != _waitBeforeLogin && !_waitBeforeLogin.IsDisposed)
                _waitBeforeLogin.Close();
        }

        private void txtFileName_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 13) return;
            SearchFileMethod();
        }

        private void txtAuthor_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 13) return;
            SearchFileMethod();
        }
    }
}
